React router的对象属性方法(一)

match对象

match是一个匹配路径参数的对象,它有一个属性params,里面的内容就是路径参数
代码示例如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import { render } from "react-dom";

import { BrowserRouter as Router, Route, Link, Prompt,Redirect } from "react-router-dom";

class Match extends Component{
render(){
return (
<div>id:{this.props.match.params.id}</div>
)
}
}

class Main extends Component{
constructor(props){
super(props);
}
render(){
return (
<Router>
<div>
<ul>
<li><Link to="/home">首页</Link></li>
<li><Link to="/other">其他页</Link></li>
</ul>

<Route path="/:id" component={Match}/>
</div>
</Router>
)
}
}
//id就是路径匹配参数。
render(<Main />,document.getElementById("root"));

Match的获取方式:
在Route component中,组件通过this.props.match获取。
在Route render 和Route children中,通过传递一个参数的方式获取。

history

是history这个为React Router提供核心功能的包。它能轻松地在客户端为项目添加基于location的导航,这种对于单页应用至关重要的功能。
React Router 是建立在 history 之上的。 简而言之,一个 history 知道如何去监听浏览器地址栏的变化, 并解析这个 URL 转化为 location 对象, 然后 router 使用它匹配到路由,最后正确地渲染对应的组件。

常用的 history 有三种形式

  1. browserHistory

  2. hashHistory

  3. createMemoryHistory

browserHistory

Browser history 是使用 React Router 的应用推荐的 history。它使用浏览器中的 History API 用于处理 URL,创建一个像example.com/some/path这样真实的 URL

hashHistory

Hash history 使用 URL 中的 hash(#)部分去创建形如 example.com/#/some/path 的路由。

history 下方法

push方法

push方法使能你跳转到新的location。通过在当前location后添加新的location时,任意的’未来’location会被清除(之前由后退按钮而形成的在当前location后的location)。

默认情况下,当你点击时,会调用history.push方法进行导航。

history.push({ pathname: '/new-place' })

go, go, go方法
最后有三个带‘go’的方法,它们分别是goBack,goForward与go。

goBack返回一层页面。实际上是将history的索引值减1。

history.goBack()

goForward与goBack相对。向前一层页面。这仅在拥有’未来’location生效,即当用户点击了后退按钮。

history.goForward()

go是一个强大的方法,并包含了goForward与goBack的功能。传入负数则退后,传入正数则向前。

history.go(-3)
请我吃辣条吧~~
-------------本文结束感谢您的阅读-------------